<template>
  <div id="listener-editor-modal" class="listener-editor-modal">
    <!-- <je-modal
      v-model:visible="visibleModule"
      :title="modalData.title"
      class=""
      :resize="false"
      @close="cancelModal"
    > -->
    <je-panel v-bind="modalData.panelOptions" style="padding-bottom: 20px">
      <template #top>
        <TopView :event-info-data="modalData.eventInfoData" @buttonActive="buttonActive" />
      </template>
      <template #left
        ><LeftView
          ref="leftView"
          :record-data="recordData"
          :event-table-data="modalData.eventTableData"
          :common-data="modalData.commonData"
          @getSelectedColumn="getSelectedColumn"
      /></template>
      <template #default>
        <DefaultView
          :record-data="recordData"
          :selected-column="modalData.selectedColumn"
          @changData="changData"
          @doSave="handlerBbar('save')"
      /></template>
      <template #bbar>
        <div class="default-bottom">
          <span
            v-for="item in modalData.bottomButtons"
            :key="item.key"
            :class="item.class"
            @click="handlerBbar(item.key)"
          >
            {{ item.text }}
          </span>
        </div>
      </template>
    </je-panel>
    <!-- /je-modal> -->
  </div>
</template>

<script>
  import { defineComponent, reactive, onMounted, nextTick, ref, watch } from 'vue';
  import { isNotEmpty, cloneDeep } from '@jecloud/utils';
  import { Modal, Panel } from '@jecloud/ui';
  import { getJsEvent, doUpdate, getData } from '@/api/index';
  import TopView from './top.vue';
  import LeftView from './left.vue';
  import DefaultView from './defaule.vue';
  import { showFuncQuerys } from '@jecloud/func';
  import { useFuncStore } from '@/store/func-store';
  import { LISTEBER_EDITOR_CONSTANT } from '@/helper/constant';

  export default defineComponent({
    name: 'ListenerEditor',
    components: {
      JePanel: Panel,
      TopView,
      LeftView,
      DefaultView,
    },
    props: {
      recordData: {
        type: Object,
        default: () => {
          return {};
        },
      },
      onCellDblclick: {
        type: Object,
        default: () => {
          return {};
        },
      },
      modalEle: Object,
    },
    emits: ['btnClick'],
    setup(props, { emit, expose }) {
      const funcStore = useFuncStore();
      const leftView = ref();
      const modalData = reactive({
        title: props.recordData.title || '脚本编辑器（Ctrl+S保存）',
        panelOptions: {
          top: { size: 80, hidden: props.recordData.eventType != 'All' },
          left: {
            size: 400,
            split: true,
            minSize: 400,
            collapsible: true,
            // hidden: props.recordData.eventType == 'default',
          },
          bbar: { size: 40 },
        },
        bottomButtons: [
          { key: 'save', text: '保存', class: 'save' },
          { key: 'sqlFilter', text: '查询拼装器', class: 'sqlFilter' },
          // { key: 'scriplibrary', text: '全局脚本库', class: 'scriplibrary' },
          // { key: 'personalScriplibrary', text: '个人脚本库', class: 'personalScriplibrary' },
        ],
        eventInfoData: [],
        eventTableData: [],
        selectedColumn: { func: props.recordData.eventInfo ? props.recordData.eventInfo : '' },
        selectedType: {},
        menuActive: { show: '', recordData: props.recordData },
        defaultEventInfo: props.recordData.eventInfo,
        newEventInfo: props.recordData.eventInfo,
        oldEventTableData: [],
        commonData: [],
      });

      const initEventData = () => {
        return new Promise((resolve) => {
          if (funcStore.eventData) {
            resolve(funcStore.eventData);
          } else {
            const j_query = {
              order: [
                { type: 'asc', code: 'VIEWEVENTS_TYPE' },
                { type: 'asc', code: 'SY_ORDERINDEX' },
              ],
              custom: [
                {
                  code: 'VIEWEVENTS_JY',
                  type: '!=',
                  value: '1',
                },
              ],
            };
            getData({
              tableCode: 'JE_CORE_VIEWEVENTS',
              limit: -1,
              j_query: JSON.stringify(j_query),
            })
              .then((data) => {
                const jsEditor = {};
                data.forEach((row) => {
                  if (!jsEditor[row.VIEWEVENTS_TYPE_CODE]) {
                    jsEditor[row.VIEWEVENTS_TYPE_CODE] = [];
                  }
                  jsEditor[row.VIEWEVENTS_TYPE_CODE].push({
                    name: row.VIEWEVENTS_NAME,
                    code: row.VIEWEVENTS_CODE,
                    func: row.VIEWEVENTS_FUNC,
                    async: row.VIEWEVENTS_YBSJ,
                  });
                });
                funcStore.eventData = jsEditor;
                resolve(jsEditor);
              })
              .catch((e) => {
                Modal.alert(e.message, 'error');
              });
          }
        });
      };
      const btnClick = () => {
        modalData.menuActive.show = '';
      };
      onMounted(() => {
        let md = document.querySelector('.listener-modal  .tool--close');
        md &&
          md.addEventListener(
            'click',
            (event) => {
              // 使用此方法可以阻止默认的事件
              event.stopImmediatePropagation();
              //改为调用自定义的方法
              handlerBbar('close');
            },
            true,
          );
        nextTick(() => {
          if (props.recordData.eventType != 'default') {
            if (props.recordData.eventType != 'All') {
              if (['form', 'grid'].indexOf(props.recordData.eventType) != -1) {
                getEventData('func');
              } else {
                getEventData(props.recordData.eventType);
              }
            } else {
              initEventData().then((res) => {
                modalData.commonData = res['common'];
              });
            }
          } else {
            // 如果是defalut的时候，props.recordData.eventInfo没有值的时候，要根据默认值的类型获取一下默认值的数据
            if (props.recordData.defaultCode) {
              if (!props.recordData.eventInfo) {
                initEventData().then((res) => {
                  const defaultArr = props.recordData.defaultCode.split(','); // [expression, common]
                  const defalutValue = res[defaultArr[0]].find(
                    (item) => item.code == defaultArr[1],
                  );
                  modalData.defaultEventInfo = modalData.newEventInfo = defalutValue?.func || '';
                  modalData.selectedColumn = { func: defalutValue?.func || '' };
                });
              }
            }
          }
        });
      });

      //获得事件信息
      const getEventData = (type, isGetData) => {
        var params = {
          funcId: props.recordData.id,
          type: type == 'actioncolumn' ? 'action' : type,
          id: props.recordData.onId,
        };
        if (props.recordData.eventType == 'All') {
          delete params.id;
        }
        initEventData()
          .then((jsEditor) => {
            modalData.jsEditor = jsEditor;
            modalData.commonData = jsEditor['common'];
            return getJsEvent(params);
          })
          .then((data) => {
            getEventInfoData(type, data, isGetData);
          })
          .catch((e) => {
            Modal.alert(e.message, 'error');
          });
      };

      //根据数据封装事件数据
      const getEventInfoData = (type, obj = [], isGetData = true) => {
        const activeItem = obj[0];
        //如果是功能
        if (props.recordData.eventType == 'All') {
          props.recordData.onId && delete props.recordData.onId;
          const eventInfoData = [];
          if (type == 'func') {
            if (isNotEmpty(activeItem?.FUNCINFO_GRIDJSLISTENER)) {
              eventInfoData.push({
                text: '列表',
                type: 'grid',
                onId: 'grid',
                eventInfo: doEventData(
                  modalData.jsEditor['grid'],
                  JSON.parse(activeItem.FUNCINFO_GRIDJSLISTENER),
                ),
              });
            }
            if (isNotEmpty(activeItem?.FUNCINFO_FORMJSLISTENER)) {
              eventInfoData.push({
                text: '表单',
                type: 'form',
                onId: 'form',
                eventInfo: doEventData(
                  modalData.jsEditor['form'],
                  JSON.parse(activeItem.FUNCINFO_FORMJSLISTENER),
                ),
              });
            }
          } else {
            obj.forEach((item) => {
              const jsColumn = LISTEBER_EDITOR_CONSTANT[type].jsColumn;
              if (isNotEmpty(item[jsColumn])) {
                const jsEvent = doEventData(
                  modalData.jsEditor[type == 'field' ? item.RESOURCEFIELD_XTYPE : type],
                  JSON.parse(item[jsColumn]),
                );
                eventInfoData.push({
                  text: item[LISTEBER_EDITOR_CONSTANT[type].text],
                  type,
                  onId: item[LISTEBER_EDITOR_CONSTANT[type].onId],
                  eventInfo: jsEvent,
                  fieldType: item.RESOURCEFIELD_XTYPE,
                });
              }
            });
          }
          modalData.eventInfoData = eventInfoData;
          modalData.oldEventTableData = isGetData ? JSON.parse(JSON.stringify(eventInfoData)) : [];
        } else {
          // 如果是单独打开的
          let jsType = props.recordData.eventType;
          const jsColumn = LISTEBER_EDITOR_CONSTANT[jsType].jsColumn;
          if (isNotEmpty(activeItem?.[jsColumn])) {
            modalData.eventTableData = doEventData(
              modalData.jsEditor[jsType == 'field' ? props.recordData.fieldType : jsType],
              JSON.parse(activeItem[jsColumn]),
            );
            modalData.oldEventTableData = JSON.parse(
              JSON.stringify(modalData.eventTableData || []),
            );
          } else {
            modalData.eventTableData = cloneDeep(
              modalData.jsEditor[jsType == 'field' ? props.recordData.fieldType : jsType],
            );
            modalData.oldEventTableData = JSON.parse(
              JSON.stringify(modalData.eventTableData || []),
            );
          }
        }
      };

      const doEventData = (eventDatas, eventTableData) => {
        const newEventDatas = [];
        eventDatas?.forEach((item) => {
          let newArr = eventTableData.filter((val) => {
            if (val.code == item.code && !val.func) {
              val.func = item.func;
            }
            return val.code == item.code;
          });
          if (newArr.length <= 0) {
            newEventDatas.push(item);
          }
        });

        if (newEventDatas.length > 0) {
          return eventTableData.concat(newEventDatas);
        } else {
          return eventTableData;
        }
      };

      //监听顶部按钮点击
      const buttonActive = (obj) => {
        if (obj.clickType == 'frist') {
          modalData.eventTableData = [];
          modalData.selectedType = {};
          modalData.selectedColumn = {};
          getEventData(obj.type, false);
        } else if (obj.clickType == 'two') {
          modalData.selectedColumn = {};
          modalData.eventTableData = obj.eventInfo;
          modalData.selectedType = { type: obj.type, onId: obj.onId };
          const data = modalData.eventInfoData.filter((item) => item.type == obj.type) || [];
          modalData.oldEventTableData = JSON.parse(JSON.stringify(data[0]?.eventInfo || []));
        }
      };

      //获得左边选中的列信息
      const getSelectedColumn = (row) => {
        modalData.selectedColumn = row;
      };
      // 保存数据
      const saveData = (flag) => {
        if (props.recordData.eventType == 'default') {
          props.onCellDblclick({ eventInfo: modalData.newEventInfo });
          modalData.defaultEventInfo = modalData.newEventInfo;
          flag && props.modalEle.close();
          return false;
        }
        // if (modalData.eventTableData.length <= 0) {
        //   return Modal.alert('请选择事件！', 'warning');
        // }
        // 参数封装
        const params = {};
        let pkValue = props.recordData.id;
        let type = props.recordData.eventType;

        if (props.recordData.eventType == 'All') {
          type = modalData.selectedType.type;
        }
        if (!type) {
          return false;
        }
        if (['grid', 'form'].indexOf(type) == -1) {
          pkValue = props.recordData.onId || modalData.selectedType.onId;
        }

        // modalData.eventTableData.map((item) => {
        //   const { fieldType } = item;
        //   const flag = funcStore.eventData[fieldType].find(
        //     (_item) => item.code == _item.code && item.func == _item.func && !item.fire,
        //   );
        //   flag && (item.func = '');
        // });
        params.tableCode = LISTEBER_EDITOR_CONSTANT[type].tableCode;
        params[LISTEBER_EDITOR_CONSTANT[type].pkColumn] = pkValue;
        params[LISTEBER_EDITOR_CONSTANT[type].jsColumn] = JSON.stringify(modalData.eventTableData);
        doUpdate(params)
          .then((data) => {
            Modal.message(data.message, 'success');
            if (props.recordData.eventType != 'All') {
              let eventType = false;
              modalData.eventTableData.forEach((item) => {
                if (item.fire == '1') {
                  eventType = true;
                }
              });
              props.onCellDblclick({
                eventType: eventType,
                data: JSON.stringify(modalData.eventTableData),
              });
            }
            modalData.oldEventTableData = JSON.parse(
              JSON.stringify(modalData.eventTableData || []),
            );
            flag && props.modalEle.close();
          })
          .catch((e) => {
            Modal.alert(e.message, 'error');
          });
      };
      //点击保存
      const handlerBbar = (type) => {
        const xTable = leftView.value && leftView.value.xTable;
        modalData.eventTableData = (xTable && xTable.getTableData().fullData) || [];
        // 判断是不是有变化
        if (type == 'close') {
          if (
            JSON.stringify(modalData.oldEventTableData) !=
              JSON.stringify(modalData.eventTableData) ||
            modalData.defaultEventInfo !== modalData.newEventInfo
          ) {
            Modal.dialog({
              content: '数据有改动，未保存，确定返回吗？',
              status: Modal.status.question,
              buttons: [
                {
                  text: '保存返回',
                  type: 'primary',
                  handler: ({ $modal }) => {
                    saveData(true);
                    $modal.close();
                  },
                },
                {
                  text: '确定返回',
                  handler: ({ $modal }) => {
                    props.modalEle.close();
                    $modal.close();
                  },
                },
                { text: '取消' },
              ],
            });
          } else {
            props.modalEle.close();
          }
        }
        if (type == 'save') {
          saveData();
        }
        if (type == 'sqlFilter') {
          showFuncQuerys({
            funcId: props.recordData.id,
            funcCode: props.recordData.code,
          });
        }
      };

      //监听事件内容修改
      const changData = (code, value) => {
        if (props.recordData.eventType == 'default') {
          modalData.newEventInfo = value;
          return false;
        }
        //后面的优化呀
        const xTable = leftView.value.xTable;
        const fullData = xTable.getTableData().fullData;
        fullData.forEach((rec) => {
          if (rec.code == code) {
            rec.func = value;
          }
        });

        /* modalData.eventTableData.forEach((item) => {
          if (code == item.code) {
            item.func = value;
          }
        }); */
      };
      expose(() => {
        handlerBbar;
      });

      return {
        visibleModule: true,
        modalData,
        buttonActive,
        getSelectedColumn,
        changData,
        btnClick,
        leftView,
        handlerBbar,
      };
    },
  });
</script>

<style lang="less" scoped>
  .listener-editor-modal {
    height: 100%;
    .default-bottom {
      height: 100%;
      padding: 0 10px;
      background: #1e1e1e;
      border-top: 1px solid #e6e6e6;
      span {
        display: inline-block;
        margin: 0 5px;
        padding: 9px;
        cursor: pointer;
        color: #f9cd90;
        &.save {
          color: #aeffa6;
        }
      }
    }
  }
</style>
<style lang="less"></style>
